<script setup lang="tsx">
import { MessagePlugin, PresetRange, NotifyPlugin } from 'tdesign-vue-next'
import { nextTick, ref } from 'vue'
import dayjs from 'dayjs'
import { useClipboard } from '@vueuse/core'
import { useUserStore } from '@renderer/store/modules/user'
import SaveReportForm from './components/SaveReportForm.vue'
import SaveReportWebView from './components/SaveReportWebView.vue'
import { storeToRefs } from 'pinia'

const gitPath = ref('')
const gitLogItems = ref<GitLogItemInfo[]>([])
const gitCurrentUser = ref('')
const gitAllCommitsUsers = ref<string[]>([])
const gitChooseCommitUsers = ref<string[]>([])
const saveReportVisible = ref(false)
const saveWebViewVisible = ref(false)

const userStore = useUserStore()

const { getUserToken } = storeToRefs(userStore)

// 监听用户token
userStore.watchUserInfo()

const dateRange = ref([
  dayjs().subtract(6, 'day').format('YYYY-MM-DD'),
  dayjs().format('YYYY-MM-DD')
])

const { copy, copied } = useClipboard()
function handleCopy(msg: string) {
  // 去掉开头的fix, feat等
  if (msg.includes('fix:') || msg.includes('feat:')) {
    //
    msg = msg.replace(/^(fix|feat):/g, '')
  }
  copy(msg)
}

// 快捷筛选日期
const presets = ref({
  最近1月: [dayjs().subtract(29, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  最近2周: [dayjs().subtract(13, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  最近7天: [dayjs().subtract(6, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  最近3天: [dayjs().subtract(2, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  今天: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
}) as unknown as PresetRange

const columns = ref([
  {
    width: 100,
    title: '提交hash',
    colKey: 'hash',
    ellipsis: true
  },
  {
    width: 180,
    title: '提交时间',
    colKey: 'date',
    ellipsis: true
  },
  {
    title: '提交信息',
    colKey: 'message',
    cell: 'cell-message'
  },
  {
    title: '提交人',
    colKey: 'author',
    ellipsis: true
  }
])

function setGitInfos(gitFolderPathInfo: GitBackInfo & GitBackInfoError, isReload: boolean = false) {
  if (gitFolderPathInfo?.isCancel) {
    MessagePlugin.info('已取消!')
    return
  }
  gitPath.value = gitFolderPathInfo.gitPath
  gitCurrentUser.value = gitFolderPathInfo.gitCurrentUser
  gitAllCommitsUsers.value = []
  gitLogItems.value = gitFolderPathInfo.gitInfo.map((git) => {
    return {
      hash: git.hash.slice(0, 7),
      date: dayjs(git.date).format('YYYY-MM-DD HH:mm:ss'),
      author: git.author,
      message: git.message
    }
  })

  //
  nextTick(() => {
    if (isReload) {
      gitChooseCommitUsers.value = [gitCurrentUser.value]
    }
    gitAllCommitsUsers.value = gitFolderPathInfo.gitAllCommitsUsers
  })
}

async function handleFormChange() {
  const date = dayjs(dateRange.value[1]).diff(dayjs(dateRange.value[0]), 'day') + 1
  const gitFolderPathInfo = await window.api.handlePreloadApiChangeGitInfos({
    day: date,
    author: JSON.stringify(gitChooseCommitUsers.value)
  })
  // 拿不到.git目录,给提示
  if (!gitFolderPathInfo) {
    MessagePlugin.error('当前项目没有git目录!')
    return
  }

  setGitInfos(gitFolderPathInfo)
}

async function handleOpenFolder() {
  // todo
  const gitFolderPathInfo = await window.api.handlePreloadApiOpenDirectoryDialog()
  // 拿不到.git目录,给提示
  if (!gitFolderPathInfo) {
    MessagePlugin.error('当前项目没有git目录!')
    return
  }

  setGitInfos(gitFolderPathInfo, true)
}

async function handleOpenNewWindow() {
  //
  window.electron.ipcRenderer.send('ipcMainOpenWindow', {
    url: 'https://qiguanbang.com/'
  })
}

function handleOpenSaveReportForm() {
  saveWebViewVisible.value = true
}

const NotifyFooter = () => {
  return (
    <div class="flex justify-end mt-2px">
      <t-button
        theme={copied.value ? 'success' : 'primary'}
        size="small"
        onClick={() => handleCopy(getUserToken.value)}
      >
        {copied.value ? '复制成功' : '复制'}
      </t-button>
    </div>
  )
}

function handleShowUserToken() {
  //
  NotifyPlugin.info({
    title: '用户token',
    content: getUserToken.value,
    duration: 1000,
    closeBtn: true,
    placement: 'bottom-right',
    footer: NotifyFooter
  })
}
</script>

<template>
  <div p20px>
    <t-alert v-if="!gitPath" theme="info" close>
      <template #message>
        <span>请先选择你的工作项目,此工具会自动读取你的git目录下的提交记录,提取提交记录信息</span>
      </template>
    </t-alert>
    <div my10px>
      <template v-if="gitPath">
        <div bg-white p-4 mb-4>
          <div flex items-center justify-between>
            <div>
              当前项目路径:<span text-red pl-2 font-bold> {{ gitPath }}</span>
            </div>
            <div flex gap-4>
              <t-button
                v-if="getUserToken"
                theme="primary"
                variant="text"
                size="small"
                @click="handleShowUserToken"
              >
                <span>查看用户token</span>
              </t-button>
              <t-button size="small" @click="handleOpenNewWindow">
                <span>获取企管帮信息</span>
              </t-button>
              <t-button theme="danger" size="small" @click="handleOpenFolder">
                <span>切换其他项目</span>
              </t-button>
              <t-button
                :disabled="!getUserToken"
                theme="success"
                size="small"
                @click="handleOpenSaveReportForm"
              >
                <span>提交日报</span>
              </t-button>
            </div>
          </div>
          <div class="mt10px" grid grid-cols-3 gap-x-4 items-center>
            <div flex items-center justify-center>
              <span class="w100px">日期范围:</span>
              <t-date-range-picker
                v-model="dateRange"
                :presets="presets"
                @change="handleFormChange"
              />
            </div>
            <div flex items-center justify-center>
              <span class="w100px">代码提交:</span>
              <t-select
                v-model="gitChooseCommitUsers"
                placeholder="请选择"
                clearable
                multiple
                :min-collapsed-num="1"
                :tag-props="{ maxWidth: 120 }"
                @change="handleFormChange"
              >
                <t-option v-for="user in gitAllCommitsUsers" :key="user" :value="user">
                  <div class="line-clamp-1 w150px">{{ user }}</div>
                </t-option>
              </t-select>
            </div>
          </div>
        </div>
        <t-table
          :columns="columns"
          :data="gitLogItems"
          row-key="index"
          cell-empty-content="-"
          resizable
          bordered
          max-height="calc(100vh - 260px)"
          :scroll="{ type: 'virtual', bufferSize: 10 }"
          lazy-load
        >
          <template #cell-message="{ row }">
            <div grid class="grid-cols-[16px_auto] items-center gap-2">
              <t-tooltip :content="copied ? '复制成功' : '点击复制'" placement="mouse">
                <span
                  cursor-pointer
                  class="w16px h16px text-orange i-ri-file-copy-line"
                  role="img"
                  aria-hidden="true"
                  @click="handleCopy(row.message)"
                />
              </t-tooltip>
              <t-tooltip :content="row.message" placement="mouse">
                <span truncate>{{ row.message }}</span>
              </t-tooltip>
            </div>
          </template>
        </t-table>
      </template>
      <template v-else>
        <div flex items-center justify-center h-500px>
          <t-button @click="handleOpenFolder">请先选择项目路径</t-button>
        </div>
      </template>
    </div>
    <SaveReportForm v-model:visible="saveReportVisible" />
    <template v-if="saveWebViewVisible">
      <SaveReportWebView v-model:webviewVisible="saveWebViewVisible" />
    </template>
  </div>
</template>

<style scoped></style>
